package com.wxxymaker.controller;

import com.blade.ioc.annotation.Inject;
import com.blade.mvc.WebContext;
import com.blade.mvc.annotation.GetRoute;
import com.blade.mvc.annotation.Path;
import com.blade.mvc.annotation.PathParam;
import com.blade.mvc.http.Request;
import com.blade.mvc.http.Response;
import com.wxxymaker.model.entity.Article;
import com.wxxymaker.service.ArticleService;
import com.wxxymaker.utils.Const;
import com.wxxymaker.utils.SimpleCache;
import io.github.biezhi.anima.page.Page;

import java.util.List;

/**
 * @Author: Soft
 * @Date: 2018/6/3 17:05
 * @Desc: 前台视图控制器
 */
@Path
public class ViewController {

    @Inject
    private ArticleService articleService;

    @GetRoute({"/", "/index"})
    public String index() {
        return "index";
    }

    @GetRoute("/news")
    public String news(Request request) {
        request.attribute("pages", new Page());
        return "news";
    }

    @GetRoute("/notice")
    public String notice(Request request) {
        request.attribute("pages", new Page());
        return "notice";
    }

    @GetRoute("/solution")
    public String solution() {
        return "solution";
    }

    @GetRoute("/result")
    public String result(Request request) {
        request.attribute("pages", new Page());
        return "result";
    }

    @GetRoute("/about")
    public String about() {
        return "about";
    }

    @GetRoute("/join")
    public String join() {
        return "join";
    }

    @GetRoute("/contact")
    public String contact() {
        return "contact";
    }

    @SuppressWarnings("unchecked")
    @GetRoute("/article/:id")
    public String showArticle(Request request,
                              Response response,
                              @PathParam Integer id) {
        String ip = request.host();
        String referer = request.header("Referer");

        Article one = articleService.findOne(id);
        if (one == null || (one.getStatus() == 0 && !referer.contains("/admin"))) {
            return "404";
        }
        if (!referer.contains("/admin")) {
            List<String> ips = (List<String>) SimpleCache.get(Const.ipKey);
            if (!ips.contains(ip + "_" + id) || null == request.cookie(Const.VisitorKey)) {
                /*
                 设置一个30分钟的cookie，用于增加用户阅读
                 不是null就认为是30分钟内
                */
                response.cookie(Const.VisitorKey, "VISITOR", 30*60);
                articleService.addView(id); // 增加阅读量
                one.setViews(one.getViews() + 1);
                ips.add(ip + "_" + id);
            }
        }
        request.attribute("article", one);
        return "show";
    }
}